package com.example.springthymeleafproject.service;

import com.example.springthymeleafproject.model.Department;
import com.example.springthymeleafproject.model.Device;
import com.example.springthymeleafproject.repository.DepartmentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class DepartmentServiceImpl implements DepartmentService{
    @Autowired
    private DepartmentRepository departmentRepository;

    //查询所有部门信息
    @Override
    public List<Department> getAllDepartment() {
        return departmentRepository.findAll();
    }

    //保存部门信息
    @Override
    public void saveDepartment(Department department) {
        this.departmentRepository.save(department);
    }

    //获取指定id的部门
    @Override
    public Department getDepartmentId(long id) {
        Optional<Department> optional = departmentRepository.findById(id);
        Department department = null;
        //如果存在指定的id的设备，则赋值给device，不存在则抛出异常
        if (optional.isPresent()){
            department = optional.get();
        } else {
            throw  new RuntimeException("找不到指定设备的id : " + id);
        }

        return department;
    }

    //分页并通过字段排序
    @Override
    public Page<Department> findDepartmentPaginated(int pageNo, int pageSize, String sortField, String sortDirection) {
        //设置排序参数，升序ASC/降序DESC？
        Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name())
                ? Sort.by(sortField).ascending()
                : Sort.by(sortField).descending();

        //根据页号/每页记录数/排序依据返回某指定页面数据。
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sort);
        return this.departmentRepository.findAll(pageable);
    }
}
